package im.yisme.model.fileio;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;

import im.yisme.model.Lyrics;
import im.yisme.model.LyricsAction;
import im.yisme.model.LyricsHeader;

public class LyricsReader {

	private String postfix = ".ylrc";
	private String path = "";
	
	public LyricsReader(){
		path = DirManager.getLyricsDir();
	}
	
	/**
	 * 从文件中读出歌谱数据
	 * @param lyrics
	 * @throws IOException
	 */
	public void read(Lyrics lyrics) throws IOException{
		File file = new File(path + lyrics.getId() + postfix);
		FileInputStream fis = new FileInputStream(file);
		int usedSize = 0;
		
		long id = readData(fis, 4);
		usedSize += 4;
		int totalTime = readData(fis, 4);
		usedSize += 4;
		int totalSize = readData(fis, 2);
		usedSize += 2;
		boolean uploaded = readData(fis, 1) == 1 ? true : false;
		usedSize += 1;
		boolean evaluated = readData(fis, 1) == 1 ? true : false;
		usedSize += 1;
		
		fis.skip(32 - usedSize);
		
		LyricsHeader header = new LyricsHeader(id, totalTime, uploaded, evaluated);
		lyrics.setLyricsHeader(header);
		
		ArrayList<LyricsAction> actions = new ArrayList<LyricsAction>();
		for(int i=0; i<totalSize; i++){
			int actionInfo = readData(fis, 4);
			LyricsAction action = new LyricsAction(actionInfo);
			actions.add(action);
		}
		lyrics.setLyricsActions(actions);
		
		fis.close();
	}
	
	/**
	 * 从fis中读出bytes个字节的数据
	 * @param fis
	 * @param bytes
	 * @return
	 * @throws IOException
	 */
	private int readData(FileInputStream fis, int bytes) throws IOException{
		int data = 0;
		for (int i=0; i<bytes; i++){
			data <<= 8;
			data += fis.read() & 0x000000ff;
		}
		return data;
	}
}
